package com.motu.vertx.module.utility.logsdk;

import com.motu.data.UserLoginDevice;
import com.motu.vertx.module.utility.commondata.CommonDataManager;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ToutiaoManager {
	private static final Logger logger = LoggerFactory.getLogger(ToutiaoManager.class);

	// 事件名称
	public static final String EVENT_REGISTER = "register";//注册事件
	public static final String EVENT_PURCHASE = "purchase";//充值事件

	// 日志类型
	public static final byte TYPE_REGISTER = 1;//注册
	public static final byte TYPE_PURCHASE = 2;//充值

	/**
	 * 获取公共参数
	 *
	 * @param eventName       事件名称
	 * @param chargePackage   应用包配置信息
	 * @param userId          用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @return 上报公共参数
	 */
	private static JsonObject getCommonParams(String eventName, ChargePackage chargePackage, long userId, UserLoginDevice userLoginDevice) {
		try {
			if (userLoginDevice == null) {
				logger.error("ToutiaoManager send error loginDeviceInfo is null userId:{} eventName:{}", userId, eventName);
				return null;
			}

			JsonObject jo = new JsonObject();  //最终包数据

			/******user部分*****/
			String open_udid = "";
			if (userLoginDevice.getRyos().equalsIgnoreCase("android")) {
				open_udid = userLoginDevice.getAndroidId();
			}
			JsonObject user = new JsonObject();
			user.put("user_unique_id", userLoginDevice.getAccountId());
			user.put("udid", userLoginDevice.getImei());
			user.put("oaid", userLoginDevice.getOaid());
			user.put("open_udid", open_udid);
			user.put("idfa", userLoginDevice.getIdfa());
			user.put("idfv", userLoginDevice.getIdfv());
			user.put("build_serial", userLoginDevice.getBuildSerial());
			/******user部分*****/
			jo.put("user", user);

			/******header部分*****/
			JsonObject header = new JsonObject();

			String app_package = chargePackage.getPackageName();     //包名，务必与真实投放的包名⼀一致
			header.put("app_package", app_package);

			String app_channel = String.valueOf(chargePackage.getChannel());      //app分发渠道
			header.put("app_channel", app_channel);

			String app_version = userLoginDevice.getAppVersion(); //app版本，三段分隔，如1.0.1
			header.put("app_version", app_version);

			String os_name = userLoginDevice.getRyos(); //客户端系统
			header.put("os_name", os_name);

			String os_version = userLoginDevice.getRyosVersion(); //客户端系统版本号
			header.put("os_version", os_version);

			String device_model = userLoginDevice.getDeviceType(); //设备型号
			header.put("device_model", device_model);

			String traffic_type = ""; //流量量类型
			header.put("traffic_type", traffic_type);

			String utm_source = ""; //
			header.put("utm_source", utm_source);

			String utm_medium = ""; //
			header.put("utm_medium", utm_medium);

			String utm_campaign = ""; //
			header.put("utm_campaign", utm_campaign);

			String client_ip = userLoginDevice.getIp(); //客户端ip
			header.put("client_ip", client_ip);

			JsonObject custom = new JsonObject(); //⾃自定义header字段,单层json map
			header.put("custom", custom);
			/******header部分*****/
			jo.put("header", header);

			return jo;
		} catch (Exception e) {
			logger.error("ToutiaoManager send error Exception:{}", Tool.getException(e));
			return null;
		}
	}

	/***
	 * 注册事件
	 * @param userId 用户ID
	 * @param userLoginDevice 用户登录设备信息
	 */
	public static void sendRegisterEvent(long userId, UserLoginDevice userLoginDevice) {

		// 获取应用包配置
		ChargePackage chargePackage = CommonDataManager.getChargePackage(ChargePackage.TYPE_TOUTIAO, userLoginDevice.getPlatform(), userLoginDevice.getChannel());
		if (chargePackage == null) {
			return;
		}

		// 获取公共参数
		JsonObject jo = getCommonParams(EVENT_REGISTER, chargePackage, userId, userLoginDevice);
		if (jo == null) {
			return;
		}

		// 设置事件参数
		JsonArray events = new JsonArray();  //事件列表
		JsonObject event = new JsonObject();  //新建事件
		event.put("event", EVENT_REGISTER);  //事件名
		JsonObject eventParams = new JsonObject();
		eventParams.put("method", "MTSDK");  //注册⽅方式
		eventParams.put("is_success", "yes");  //是否成功
		eventParams.put("is_server", "yes");  //支付金额
		event.put("params", eventParams.toString()); //事件参数,单层json map
		event.put("local_time_ms", System.currentTimeMillis()); //unix_timestamp(毫秒)
		events.add(event);
		/******events部分*****/
		jo.put("events", events);

		JsonObject obj = new JsonObject()
				.put("type", TYPE_REGISTER)
				.put("url", chargePackage.getToutiaoUrl())
				.put("data", jo)
				.put("key", chargePackage.getToutiaoKey());
		LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_TOUTIAO, obj);
	}

	/***
	 * 充值事件
	 * @param userId 用户ID
	 * @param userLoginDevice 用户登录设备信息
	 * @param money 付费金额（人民币金额）
	 */
	public static void sendChargeEvent(long userId, UserLoginDevice userLoginDevice, double money) {

		// 获取应用包配置
		ChargePackage chargePackage = CommonDataManager.getChargePackage(ChargePackage.TYPE_TOUTIAO, userLoginDevice.getPlatform(), userLoginDevice.getChannel());
		if (chargePackage == null) {
			return;
		}

		// 获取公共参数
		JsonObject jo = getCommonParams(EVENT_PURCHASE, chargePackage, userId, userLoginDevice);
		if (jo == null) {
			return;
		}

		// 设置事件参数
		JsonArray events = new JsonArray();  //事件列表
		JsonObject event = new JsonObject();  //新建事件
		event.put("event", EVENT_PURCHASE);  //事件名
		JsonObject params = new JsonObject();
		params.put("currency", "CNY");  //货币类型
		params.put("is_success", "yes");  //是否成功
		params.put("currency_amount", Tool.rint(money));  //支付金额
		event.put("params", params.toString()); //事件参数,单层json map
		event.put("local_time_ms", System.currentTimeMillis()); //unix_timestamp(毫秒)
		events.add(event);
		/******events部分*****/
		jo.put("events", events);

		JsonObject obj = new JsonObject()
				.put("type", TYPE_PURCHASE)
				.put("url", chargePackage.getToutiaoUrl())
				.put("data", jo)
				.put("key", chargePackage.getToutiaoKey());
		LogSDKManager.pushToQueue(LogSDKManager.KAFKA_TOPIC_TOUTIAO, obj);
	}
	
}
